//
//  SHECustomViewController.m
//  SHEPuzzleFigure
//
//  Created by SW mini on 2019/11/27.
//  Copyright © 2019 Figure. All rights reserved.
//

#import "SHECustomViewController.h"
#import "SHESelectTypeView.h"

@interface SHECustomViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *dateTabel;
@property (weak, nonatomic) IBOutlet UILabel *numberLabel;
@property (weak, nonatomic) IBOutlet UIView *puzzleView;
@property (weak, nonatomic) IBOutlet UIButton *difficultyBtn;
@property (strong,nonatomic)dispatch_source_t sourceTimer;
@property (assign,nonatomic)NSInteger gcdIdx;
@property (assign,nonatomic)NSInteger numIdx;

#pragma mark - 选项
/// 图片
@property (nonatomic, strong) UIImage *image;
/// 选择图片
@property (nonatomic, strong) UIImage *selectImage;
@property (strong, nonatomic) NSData *imagedata;
/// 矩阵阶数
@property (nonatomic, assign) NSInteger matrixOrder;

#pragma mark - 状态
/// 当前游戏状态
@property (nonatomic, strong) PuzzleStatus *currentStatus;
/// 完成时的游戏状态
@property (nonatomic, strong) PuzzleStatus *completedStatus;
/// 保存的游戏状态
@property (nonatomic, strong) PuzzleStatus *savedStatus;

@end

@implementation SHECustomViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [super setTitleView:@"自定义"];
    [super createBackBtn];

    SHELoadingView *loadingView = [SHELoadingView initWithXib:CGRectMake(0, 0, SCREEN_WIDTH_S, SCREEN_MAX_LENGTH_S)];
    [[UIApplication sharedApplication].keyWindow addSubview:loadingView];
    [loadingView start];
 
    self.matrixOrder = 3;//难度
    
    self.puzzleView.frame = CGRectMake(15, 155, SHEWidth-30, SHEWidth-30);
    
    [self updateImageUi];
    
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    self.gcdIdx = 0;
    self.numIdx = 0;
    //开启计时器
    [self createDispatch_source_t];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //关闭计时器
    dispatch_source_cancel(self.sourceTimer);
}


- (void)updateImageUi{
    //初始化图片
    if (self.selectImage) {
        self.image = self.selectImage;
    }else{
        self.image = [UIImage imageNamed:@"11"];
    }
    //消失一格
    [self onPieceTouch:self.currentStatus.pieceArray.lastObject];
    //打乱
    [self onShuffleMethods];
    
    
}
- (void)setImage:(UIImage *)image {
    _image = image;
    [self onResetTheGame];
}

//保存进度,读取进度,重新开始 难度，自选图片
- (IBAction)clickBtn:(UIButton *)sender {
    switch (sender.tag) {
        case 1003:{//保存进度
            [self onSaveProgress];
        }
            break;
        case 1004:{//读取进度
            [self onLoadProgress];
        }
            break;
        case 1005:{//重新开始
            [self onResetTheGame];
            [self updateImageUi];
        }
            break;
        case 1006:{//难度选择
            [self onHardDifficultySwitch];
        }
            break;
        case 1007:{//自选图片
            [self onSelectPicturePhoto];
        }
            break;
    }
}

/// 打乱顺序
- (void)onShuffleMethods {
    
    if (self.currentStatus.emptyIndex < 0) {
        return;
    }
    NSLog(@"打乱顺序：当前为%@阶方阵, 随机移动%@步", @(self.matrixOrder), @(self.matrixOrder * self.matrixOrder * 2));
    [self.currentStatus shuffleCount:self.matrixOrder * self.matrixOrder * 2];
    [self reloadWithStatus:self.currentStatus];
}

/// 重置游戏
- (void)onResetTheGame {
    
    if (!self.image) {
        return;
    }
    
    if (self.currentStatus) {
        [self.currentStatus removeAllPieces];
    }
    self.currentStatus = [PuzzleStatus statusWithMatrixOrder:self.matrixOrder image:self.image];
    [self.currentStatus.pieceArray enumerateObjectsUsingBlock:^(PuzzlePiece * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj addTarget:self action:@selector(onPieceTouch:) forControlEvents:UIControlEventTouchUpInside];
    }];
    
    self.completedStatus = nil;
    [self showCurrentStatusOnView:self.puzzleView];
}

/// 保存进度
- (void)onSaveProgress {
    
    if (!self.currentStatus) {
        return;
    }
    
    self.savedStatus = [self.currentStatus  copyStatus];
    [self alertTitle:nil message:@"保存成功,仅在本局内有效"];
}

/// 读取进度
- (void)onLoadProgress  {
    
    if (!self.savedStatus) {
        return;
    }
    
    if (self.currentStatus) {
        [self.currentStatus removeAllPieces];
    }
    self.currentStatus = self.savedStatus;
    
    [self showCurrentStatusOnView:self.puzzleView];
    [self alertTitle:nil message:@"读取成功"];
}

/// 点击方块
- (void)onPieceTouch:(PuzzlePiece *)piece {
    
    PuzzleStatus *status = self.currentStatus;
    NSInteger pieceIndex = [status.pieceArray indexOfObject:piece];
    
    // 挖空一格
    if (status.emptyIndex < 0) {
        // 所选方块成为空格
        [UIView animateWithDuration:0.25 animations:^{
            piece.alpha = 0;
        }];
        status.emptyIndex = pieceIndex;
        // 设置目标状态
        self.completedStatus = [self.currentStatus  copyStatus];
        return;
    }
    
    if (![status canMoveToIndex:pieceIndex]) {
        NSLog(@"无法移动，target index:%@",  @(pieceIndex));
        return;
    }
    
    [status moveToIndex:pieceIndex];
    [self reloadWithStatus:self.currentStatus];
    
    // 完成一次移动
    self.numberLabel.text = [NSString stringWithFormat:@"步数：%ld",++self.numIdx];
    if ([status equalWithStatus:self.completedStatus]) {
        [self alertTitle:@"恭喜" message:@"拼图完成！"];
    }
}

- (void)showCurrentStatusOnView:(UIView *)view {
    CGFloat size = CGRectGetWidth(view.bounds) / self.matrixOrder;
    NSInteger index = 0;
    for (NSInteger row = 0; row < self.matrixOrder; ++ row) {
        for (NSInteger col = 0; col < self.matrixOrder; ++ col) {
            PuzzlePiece *piece = self.currentStatus.pieceArray[index ++];
            piece.frame = CGRectMake(col * size, row * size, size, size);
            [view addSubview:piece];
        }
    }
}

- (void)reloadWithStatus:(PuzzleStatus *)status {
    [UIView animateWithDuration:0.25 animations:^{
        CGSize size = status.pieceArray.firstObject.frame.size;
        NSInteger index = 0;
        for (NSInteger row = 0; row < self.matrixOrder; ++ row) {
            for (NSInteger col = 0; col < self.matrixOrder; ++ col) {
                PuzzlePiece *piece = status.pieceArray[index ++];
                piece.frame = CGRectMake(col * size.width, row * size.height, size.width, size.height);
            }
        }
    }];
}
/// 选择图片
- (void)onSelectPicturePhoto {

    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf selectImageWithSourceType:UIImagePickerControllerSourceTypeCamera];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf selectImageWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"默认图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        weakSelf.selectImage = nil;
        weakSelf.image = [UIImage imageNamed:@"11"];
        [weakSelf updateImageUi];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}
/// 难度切换
- (void)onHardDifficultySwitch {
    SHESelectTypeView *view = [SHESelectTypeView initWithXib:CGRectMake(0, 0, SCREEN_WIDTH_S, SCREEN_MAX_LENGTH_S)];
    __weak typeof(self) weakSelf = self;
    view.SelectBlock = ^(int type) {
        weakSelf.matrixOrder = type;
        [weakSelf updateImageUi];
    };
    [self.view addSubview:view];
}
//难度
- (void)setMatrixOrder:(NSInteger)matrixOrder {
    if (matrixOrder < 3 || matrixOrder > 5) {
        return;
    }
    _matrixOrder = matrixOrder;
    NSString *title;
    if (matrixOrder == 3) {
        title = @"难度：低";
        [self.difficultyBtn setImage:[UIImage imageNamed:@"zi_6"] forState:UIControlStateNormal];
    }
    else if (matrixOrder == 4) {
        title = @"难度：中";
        [self.difficultyBtn setImage:[UIImage imageNamed:@"zi_12"] forState:UIControlStateNormal];
    }
    else if (matrixOrder == 5) {
        title = @"难度：高";
        [self.difficultyBtn setImage:[UIImage imageNamed:@"zi_13"] forState:UIControlStateNormal];
    }
    [self onResetTheGame];
}

/// 用户提示
- (void)alertTitle:(NSString *)title message:(NSString *)message {
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    NSLog(@"内存警告");
}

//计时器
-(void)createDispatch_source_t{
    //创建全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //使用全局队列创建计时器
    _sourceTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //定时器延迟时间
    NSTimeInterval delayTime = 1.0f;
    //定时器间隔时间
    NSTimeInterval timeInterval = 1.0f;
    //设置开始时间
    dispatch_time_t startDelayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC));
    //设置计时器
    dispatch_source_set_timer(_sourceTimer,startDelayTime,timeInterval*NSEC_PER_SEC,0.1*NSEC_PER_SEC);
    //执行事件
    dispatch_source_set_event_handler(_sourceTimer,^{
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dateTabel.text = [NSString stringWithFormat:@"时间：%lds",self.gcdIdx++];
        });
        
    });
    //启动计时器
    dispatch_resume(self.sourceTimer);
}


/// 选择图片
- (void)selectImageWithSourceType:(UIImagePickerControllerSourceType)sourceType {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = sourceType;
    picker.allowsEditing = YES;
    [self.navigationController presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        self.image = info[UIImagePickerControllerEditedImage];
        self.selectImage = info[UIImagePickerControllerEditedImage];
        [self updateImageUi];
        

        //UIImage转换为NSData
        self.imagedata = UIImagePNGRepresentation(self.selectImage);

    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
